package com.dirox.jira.notes.utils;

import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.sal.api.ApplicationProperties;
import static com.atlassian.streams.api.Html.html;
import com.atlassian.streams.api.common.Either;
import static com.atlassian.streams.api.common.Option.some;
import com.atlassian.streams.thirdparty.api.Activity;
import com.atlassian.streams.thirdparty.api.ActivityService;
import static com.atlassian.streams.thirdparty.api.Application.application;
import com.atlassian.streams.thirdparty.api.ValidationErrors;
import static com.google.common.base.Preconditions.checkNotNull;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;


/**
 *
 * This class is used for posting an activity
 *
 * @author thuan
 *
 */
public class ActivityHelper {
	private static final Logger log = LoggerFactory.getLogger(
		ActivityHelper.class);
	private ActivityService activityService;
	private JiraAuthenticationContext context;
	private ApplicationProperties applicationProperties;

	public void setActivityService(ActivityService activityService) {
		this.activityService = checkNotNull(activityService);
	}

	public void setContext(JiraAuthenticationContext context) {
		this.context = checkNotNull(context);
	}

	public void setApplicationProperties(ApplicationProperties applicationProperties) {
		this.applicationProperties = checkNotNull(applicationProperties);
	}

	public void postActivitity(String applicationDisplayName, String title,
	                           String content) {
		Activity.Builder builder = new Activity.Builder(
			application(
				applicationDisplayName,
				URI.create(applicationProperties.getBaseUrl())),
			new DateTime(),
			new com.atlassian.streams.api.UserProfile.Builder(
				context.getLoggedInUser().getName()).build());

		Either<ValidationErrors, Activity> result = builder.content(
			some(html(content)))
		                                                   .title(
			some(html(title)))
		                                                   .url(
			some(URI.create(applicationProperties.getBaseUrl())))
		                                                   .build();

		for (Activity activity : result.right()) {
			activityService.postActivity(activity);
		}

		for (ValidationErrors errors : result.left()) {
			log.error(
				"Errors encountered attempting to post activity: "
				+ errors.toString());
		}
	}
}
